package top.hepingan.java.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import top.hepingan.java.common.Result;
import top.hepingan.java.entity.User;
import top.hepingan.java.mapper.UserMapper;
import top.hepingan.java.service.IUserService;
import top.hepingan.java.utils.UserUtils;
import top.hepingan.java.utils.WechatUtil;

import java.time.LocalDateTime;

@RequestMapping("/user")
@RestController
@Slf4j
@RequiredArgsConstructor
public class UserController {


    private final UserMapper userMapper;

    private final IUserService userService;

    private final WechatUtil wechatUtil;



    /**
     * 微信登录
     * @param code
     * @return
     */
    @PostMapping("/wx-login")
    public Result wxLogin(@RequestBody String code) {
        String openId = wechatUtil.getOpenId(code);
        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getOpenId, openId));
        if (user == null) {
            user = new User();
            user.setOpenId(openId);
            user.setUsername("wx_"+openId.substring(6, 12));
            user.setRole("user");
            user.setAvatar("https://img-hepingan.oss-cn-hangzhou.aliyuncs.com/page/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            user.setLastLoginTime(LocalDateTime.now());
            user.setCreatedTime(LocalDateTime.now());
            userMapper.insert(user);
            StpUtil.login(user.getId());
            return Result.data(StpUtil.getTokenInfo());
        }else {
            user.setLastLoginTime(LocalDateTime.now());
            userMapper.updateById(user);
            StpUtil.login(user.getId());
            return Result.data(StpUtil.getTokenInfo());
        }
    }


    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody User user){
        User u = userMapper.selectOne(new QueryWrapper<User>().lambda()
                .eq(User::getId, UserUtils.getCurrentLoginId()));
        if (u != null){
            u.setWechatId(user.getWechatId());
            u.setUsername(user.getUsername());
            u.setAvatar(user.getAvatar());
            u.setPhone(user.getPhone());
            userService.updateById(u);
           return Result.ok();
        }else {
            return Result.error("用户不存在");
        }
    }

    /**
     * 获取登录用户信息
     * @return
     */
    @GetMapping("/getUserInfo")
    public Result getUserInfo(){
        User u = userMapper.selectById(UserUtils.getCurrentLoginId());
        return Result.data(u);
    }






}
